package com.atguigu.ssyx.product.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.atguigu.ssyx.product.config.OSSProperties;
import com.atguigu.ssyx.product.service.FileUploadService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private OSSProperties ossProperties;
    @Override
    public String fileUpload(MultipartFile file) throws Exception {
        try {
            // 1.创建client
            OSS client=new OSSClientBuilder().build(ossProperties.getEndPoint(), ossProperties.getAccessKey(),ossProperties.getSecretKey());
            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            //生成随机唯一值，使用uuid，添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            fileName = uuid+fileName;
            //按照当前日期，创建文件夹，上传到创建文件夹里面
            //  2021/02/02/01.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = timeUrl+"/"+fileName;
            //调用方法实现上传
            client.putObject(ossProperties.getBucketName(), fileName, inputStream);

            // 生成1小时有效期的签名URL
            //注！这种方式可以解决私有存储的访问图片问题，但对于商品图这种表单还是推荐设置bucket为公共读写
            // 私有更适合身份证，合同等信息
//            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
//            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(ossProperties.getBucketName(), fileName);
//            request.setExpiration(expiration);
//            URL signedUrl = client.generatePresignedUrl(request);
            // 关闭OSSClient。
            client.shutdown();
            //上传之后文件路径
            // https://ssyx-atguigu.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://"+ossProperties.getBucketName()+"."+ossProperties.getEndPoint()+"/"+fileName;
            //返回
            return url;
        }catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}